import React, { useState, useEffect, useRef } from 'react';
import './a.css';

const CustomerServiceChat = () => {
    const [messages, setMessages] = useState([]);
    const [inputText, setInputText] = useState('');
    const [isConnected, setIsConnected] = useState(false);
    const [userType, setUserType] = useState('customer');
    const [userId, setUserId] = useState(null);
    const ws = useRef(null);
    const messagesEndRef = useRef(null);
    const reconnectTimeout = useRef(null);

    // 自动滚动到最新消息
    const scrollToBottom = () => {
        messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
    };

    useEffect(() => {
        scrollToBottom();
    }, [messages]);

    // WebSocket连接
    useEffect(() => {
        const connectWebSocket = () => {
            if (ws.current && ws.current.readyState === WebSocket.OPEN) {
                return;
            }

            console.log('尝试连接WebSocket服务器...');
            
            try {
                const wsUrl = 'ws://localhost:8080';
                console.log('正在连接到:', wsUrl);
                
                ws.current = new WebSocket(wsUrl);

                ws.current.onopen = () => {
                    console.log('WebSocket连接已建立');
                    setIsConnected(true);
                    if (reconnectTimeout.current) {
                        clearTimeout(reconnectTimeout.current);
                        reconnectTimeout.current = null;
                    }
                    
                    // 设置用户类型
                    ws.current.send(JSON.stringify({
                        type: 'setUserType',
                        userType: userType
                    }));

                    setMessages(prev => [...prev, {
                        id: Date.now(),
                        type: 'system',
                        text: '已连接到客服系统',
                        time: new Date().toLocaleTimeString()
                    }]);
                };

                ws.current.onmessage = (event) => {
                    const data = JSON.parse(event.data);
                    if (data.type === 'register') {
                        setUserId(data.userId);
                        setMessages(prev => [...prev, {
                            id: Date.now(),
                            type: 'system',
                            text: `您已加入聊天，您的ID是: ${data.userId}`,
                            time: new Date().toLocaleTimeString()
                        }]);
                    } else if (data.type === 'message') {
                        // 只显示发送给自己的消息
                        if ((userType === 'customer' && data.fromUserType === 'service') ||
                            (userType === 'service' && data.fromUserType === 'customer')) {
                            setMessages(prev => [...prev, {
                                id: Date.now(),
                                type: data.fromUserType === userType ? 'sent' : 'received',
                                text: data.message,
                                time: data.timestamp
                            }]);
                        }
                    }
                };

                ws.current.onclose = () => {
                    console.log('WebSocket连接已关闭');
                    setIsConnected(false);
                    setMessages(prev => [...prev, {
                        id: Date.now(),
                        type: 'system',
                        text: '连接已断开，正在尝试重新连接...',
                        time: new Date().toLocaleTimeString()
                    }]);

                    // 自动重连
                    if (!reconnectTimeout.current) {
                        reconnectTimeout.current = setTimeout(() => {
                            connectWebSocket();
                        }, 3000);
                    }
                };

                ws.current.onerror = (error) => {
                    console.error('WebSocket错误:', error);
                    setIsConnected(false);
                };
            } catch (error) {
                console.error('WebSocket连接错误:', error);
                setIsConnected(false);
            }
        };

        connectWebSocket();

        return () => {
            if (reconnectTimeout.current) {
                clearTimeout(reconnectTimeout.current);
            }
            if (ws.current) {
                ws.current.close();
            }
        };
    }, [userType]);

    // 发送消息
    const sendMessage = () => {
        if (!inputText.trim() || !isConnected) return;

        const messageData = {
            type: 'message',
            message: inputText
        };

        ws.current.send(JSON.stringify(messageData));
        setMessages(prev => [...prev, {
            id: Date.now(),
            type: 'sent',
            text: inputText,
            time: new Date().toLocaleTimeString()
        }]);
        setInputText('');
    };

    // 切换用户类型
    const toggleUserType = () => {
        const newUserType = userType === 'customer' ? 'service' : 'customer';
        setUserType(newUserType);
        if (ws.current && ws.current.readyState === WebSocket.OPEN) {
            ws.current.send(JSON.stringify({
                type: 'setUserType',
                userType: newUserType
            }));
        }
    };

    return (
        <div className="chat-container">
            <div className="chat-header">
                <div className="header-title">
                    {userType === 'customer' ? '在线客服' : '客服工作台'}
                </div>
                <div className="connection-status">
                    <span className={`status-dot ${isConnected ? 'connected' : ''}`}></span>
                    {isConnected ? '在线' : '离线'}
                </div>
                {userId && (
                    <div className="user-id">
                        用户ID: {userId}
                    </div>
                )}
                <button className="toggle-role" onClick={toggleUserType}>
                    切换角色
                </button>
            </div>

            <div className="chat-messages">
                {messages.map(message => (
                    <div 
                        key={message.id} 
                        className={`message ${message.type === 'system' ? 'system-message' : 
                                           message.type === 'sent' ? 'sent' : 'received'}`}
                    >
                        {message.type === 'system' ? (
                            <div className="system-content">{message.text}</div>
                        ) : (
                            <>
                                <div className="message-content">
                                    <div className="message-text">{message.text}</div>
                                    <div className="message-time">{message.time}</div>
                                </div>
                                {message.type === 'received' && (
                                    <div className="avatar">{userType === 'customer' ? '客服' : '用户'}</div>
                                )}
                                {message.type === 'sent' && (
                                    <div className="avatar">我</div>
                                )}
                            </>
                        )}
                    </div>
                ))}
                <div ref={messagesEndRef} />
            </div>

            <div className="chat-input">
                <input
                    type="text"
                    value={inputText}
                    onChange={(e) => setInputText(e.target.value)}
                    onKeyPress={(e) => e.key === 'Enter' && sendMessage()}
                    placeholder={isConnected ? "请输入消息..." : "连接中..."}
                    disabled={!isConnected}
                />
                <button 
                    className="send-button"
                    onClick={sendMessage}
                    disabled={!isConnected || !inputText.trim()}
                >
                    发送
                </button>
            </div>
        </div>
    );
};

export default CustomerServiceChat; 